package util.ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.PropertyResourceBundle;


import sun.net.ftp.FtpClient;
import sun.net.TelnetInputStream;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class Ftp {

	private static FtpClient ftp;
	private static String host;
	private static int port;
	private static String username;
	private static String password;
	private static String billFileName;
	private final static String fileName = "ftp";
	private static ThreadLocal connection = new ThreadLocal();
	static {
		config();
	}
	
	private static void config() {
		PropertyResourceBundle resourceBundle = (PropertyResourceBundle) PropertyResourceBundle
				.getBundle(fileName);
		Enumeration enu = resourceBundle.getKeys();
		while (enu.hasMoreElements()) {
			String propertyName = enu.nextElement().toString();
			if (propertyName.equals("ftp.host"))
				host = resourceBundle.getString("ftp.host");
			if (propertyName.equals("ftp.port"))
				port = Integer.parseInt(resourceBundle.getString("ftp.port"));
			if (propertyName.equals("ftp.username"))
				username = resourceBundle.getString("ftp.username");
			if (propertyName.equals("ftp.password"))
				password = resourceBundle.getString("ftp.password");
			if (propertyName.equals("ftp.billFileName"))
				billFileName = resourceBundle.getString("ftp.billFileName");
		}
	}
	
	public synchronized static ArrayList<Hashtable> getFile() throws Exception {
		ArrayList<Hashtable> items = new ArrayList<Hashtable>();
		
		ftp = new FtpClient(host, port);
		ftp.login(username, password);
		ftp.binary();
		
		try {
			TelnetInputStream tis = ftp.get(billFileName);
			InputStreamReader isreader = new InputStreamReader(tis, "MS950");
			BufferedReader reader = new BufferedReader(isreader);
		
			String sourceData;
			String[] sourceDatas;
			
			Hashtable ht;
			while((sourceData = reader.readLine()) != null) 
			{
				sourceDatas = sourceData.split(",");
				ht = new Hashtable();
				for (int i = 0; i < sourceDatas.length; i++) {
					ht.put(i, sourceDatas[i].trim());
				}
				items.add(ht);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// jk: 加了後會變很慢
		//finally{
		//	ftp.closeServer(); 
		//}
		return items;
	}
	
	public static void main(String[] args) {
		try {
			//Database.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
